using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class Table : DbObject
	{
		private DbCollection<Column> _columns = null;
		private PrimaryKey _primaryKey = null;
		private DbCollection<ForeignKey> _foreignKeys = null;
		private DbIndexCollection _indexes = null;

		public Table() : this("", 0) { }

		public Table(string name, int id)
			: base(name, id)
		{
			this._columns = new DbCollection<Column>();
			this._foreignKeys = new DbCollection<ForeignKey>();
			this._indexes = new DbIndexCollection(this);
		}

		public DbCollection<Column> Columns
		{
			get { return _columns; }
		}

		public PrimaryKey PrimaryKey
		{
			get { return _primaryKey; }
			internal set { _primaryKey = value; }
		}

		public DbCollection<ForeignKey> ForeignKeys
		{
			get { return _foreignKeys; }
		}

		public DbIndexCollection Indexes
		{
			get { return _indexes; }
		}

		public override DbObjectType Type
		{
			get { return DbObjectType.Table; }
		}

		public override void SaveXml(XmlDocument doc, XmlNode xmlParent)
		{
			XmlElement el = CreateXmlElement(doc, xmlParent);

			_columns.SaveXml(doc, el);

			// save primary key indexid
			if ( _primaryKey != null )
			{
				XmlElement xmlPK = doc.CreateElement("PrimaryKey");
				el.AppendChild(xmlPK);

				xmlPK.Attributes.Append(doc.CreateAttribute("indexid")).Value = _primaryKey.IndexID.ToString();
			}

			_indexes.SaveXml(doc, el);
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			XmlNodeList nodes = el.GetElementsByTagName(_columns.XmlElementName);
			if ( nodes.Count > 0 )
				_columns.LoadXml(nodes[0] as XmlElement, db);

			string ivalue = "";
			short pkindexid = 0;

			nodes = el.GetElementsByTagName("PrimaryKey");
			if ( nodes.Count > 0 )
			{
				XmlElement xmlPK = nodes[0] as XmlElement;

				if ( xmlPK != null )
				{
					ivalue = xmlPK.GetAttribute("indexid");
					if ( !short.TryParse(ivalue, out pkindexid) )
						pkindexid = 0;
				}
			}

			nodes = el.GetElementsByTagName(_indexes.XmlElementName);
			if ( nodes.Count > 0 )
			{
				_indexes.LoadXml(nodes[0] as XmlElement, db);
			}

			if ( _indexes.Count > 0 && pkindexid != 0 )
			{
				_primaryKey = _indexes.RetrieveByIndexID(pkindexid) as PrimaryKey;
			}
		}
	}
}
